package com.example.education.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;

@Controller
public class ImgController {
    private static final String IMG_PATH = "/var/img/";

    @GetMapping("/imgController/{imgName}")
    public void getImg(HttpServletResponse response, @PathVariable("imgName") String imgName) {
        FileInputStream fis = null;
        ServletOutputStream out = null;
        try {
            fis = new FileInputStream(IMG_PATH + imgName);
            out = response.getOutputStream();
            byte b[] = new byte[1024];
            while ((fis.read(b, 0, b.length)) != -1) {
                out.write(b);
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (fis != null) {
                try {
                    fis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (out != null) {
                try {
                    out.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
